﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Common;
using CNCSoft.ErpApps.TMS.myclass;
using CNCSoft.EData;
using CrystalDecisions.CrystalReports.Engine;

namespace CNCSoft.ErpApps.TMS.longGiaoVu
{
    public partial class frmBaoLuuHocPhi : Form
    {
        private SqlConnection conn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);
        private DataSet ds = new DataSet();
        private CommonClass mine = new CommonClass();

        private IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

        private string _userid = GlobalVariable.WSInfo.UserID;

        private DateTime _ngaykhaigiang;
        private DateTime _ngayketthuc;
        private double _sotien1hhoc = 0;
        private double _sotienbaoluu = 0;

        private bool _update = false;
        private bool _insert = false;
        private bool _delete = false;

        private DataRow _dr;

        private string _mangaytrongtuan = "";

        public string Mangaytrongtuan
        {
            get { return _mangaytrongtuan; }
            set { _mangaytrongtuan = value; }
        }
        private string _sogiohoc = "";

        public string Sogiohoc
        {
            get { return _sogiohoc; }
            set { _sogiohoc = value; }
        }

        private string _builling = "";

        public string Builling
        {
            get { return _builling; }
            set { _builling = value; }
        }

        private string _amount = "";

        public string Amount
        {
            get { return _amount; }
            set { _amount = value; }
        }
        private string _ten = "";

        public string Ten
        {
            get { return _ten; }
            set { _ten = value; }
        }
        private string _holot = "";

        public string Holot
        {
            get { return _holot; }
            set { _holot = value; }
        }
        private string _makhoahoc = "";

        public string Makhoahoc
        {
            get { return _makhoahoc; }
            set { _makhoahoc = value; }
        }
        private string _invoicenumber = "";

        public string Invoicenumber
        {
            get { return _invoicenumber; }
            set { _invoicenumber = value; }
        }
        private string _hoten = "";

        public string Hoten
        {
            get { return _hoten; }
            set { _hoten = value; }
        }

        public frmBaoLuuHocPhi()
        {
            InitializeComponent();
        }

        private void frmBaoLuuHocPhi_Load(object sender, EventArgs e)
        {
            if (_userid.ToLower() == "tuptc")
                dateEditNgayBaoLuu.Enabled = true;
            else
                dateEditNgayBaoLuu.Enabled = false;
            LoadControl();
            /*
            btnThem.Enabled = true;
            pnlTop.Enabled = false;
            pnlTop2.Enabled = false;
            pnlTop3.Enabled = false;
             */
            SetEditModeButton(false);
            SetEditModePanel(false);
            pnlTop.Enabled = false;
        }

        private void searchLookUpEditKhoaHoc_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Makhoahoc = searchLookUpEditKhoaHoc.EditValue.ToString();
                LoadInvoiceByKhoaHoc(Makhoahoc);
                searchLookUpEditInvoice.Properties.DataSource = ds.Tables["TableInvoiceByKhoaHoc"];
                searchLookUpEditInvoice.Properties.ValueMember = "InvoiceNumber";
                searchLookUpEditInvoice.Properties.DisplayMember = "Ten";

                _sogiohoc = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][4].ToString();
                _mangaytrongtuan = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][5].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void searchLookUpEditInvoice_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Invoicenumber = searchLookUpEditInvoice.EditValue.ToString();
                LoadInvoiceByInvoiceNumber(Invoicenumber);
                Holot = ds.Tables["TableInvoiceByInvoiceNumber"].Rows[0][0].ToString();
                Ten = ds.Tables["TableInvoiceByInvoiceNumber"].Rows[0][1].ToString();
                Hoten = Holot + " " + Ten;
                LoadInvoiceByInvoiceNumberAndMaKhoaHoc(Invoicenumber, Makhoahoc);
                Amount = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][4].ToString();
                Builling = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][5].ToString();
                //--------------------Go to chi tiet bao luu---------------------------------------------
                if (CheckBaoLuuByHocVienVaKhoaHoc())
                {
                    Makhoahoc = searchLookUpEditKhoaHoc.EditValue.ToString();
                    Invoicenumber = searchLookUpEditInvoice.EditValue.ToString();

                    //LoadInvoiceByKhoaHoc(Makhoahoc);
                    _sogiohoc = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][6].ToString();
                    _mangaytrongtuan = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][7].ToString();

                    //frmChiTiet = new frmBaoLuuHocPhiChiTiet(Makhoahoc, Invoicenumber, Hoten, Amount, Builling, Sogiohoc, Mangaytrongtuan);
                    //frmChiTiet.ShowDialog(this);

                    pnlTop2.Enabled = true;
                    lblTenHocSinh.Text = Hoten;
                    //---------------------------------Info cua khoa hoc----------------------------------------------------------------
                    LoadKhoaHocByKhoaHoc(_makhoahoc);
                    lblTenLop.Text = searchLookUpEditKhoaHoc.EditValue.ToString();
                    lblNgayKhaiGiang.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][1].ToString();
                    lblNgayKetThuc.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][2].ToString();
                    _ngaykhaigiang = DateTime.Parse(lblNgayKhaiGiang.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    _ngayketthuc = DateTime.Parse(lblNgayKetThuc.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    //-------------------------------------------------------------------------------------------------------------------------
                    dateEditNgayBaoLuu.EditValue = DateTime.Now.ToShortDateString();
                    //int songaydahoc = SoNgayDaHoc(ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue));

                    if (KetQua(_ngaykhaigiang, _ngayketthuc, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)))
                    {
                        lblKetQua.Text = "Bạn có thể được bảo lưu do thời gian học của bạn chưa đạt được 1/2 trên tổng thời gian của khóa học.";
                        pnlTop3.Enabled = true;
                        lblSoTienDaDong.Text = String.Format("{0:C}", Convert.ToDouble(_amount));
                        lblTenHocSinh.Text = _hoten;
                        lblPhiBaoLuu.Text = String.Format("{0:C}", 300000);
                        _sotien1hhoc = SoTien1hHoc(Convert.ToDouble(_builling), Convert.ToInt32(_sogiohoc));
                        lblSoTien1hHoc.Text = String.Format("{0:C}", _sotien1hhoc);
                        _sotienbaoluu = SoTienBaoLuu(Convert.ToDouble(_amount), _sotien1hhoc,
                                                        SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)));
                        lblSoTienBaoLuu.Text = String.Format("{0:C}", _sotienbaoluu);
                        lblSoGioDaHoc.Text = SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)).ToString();
                        lblNgayKetThucBaoLuu.Text = TinhNgayKetThucBaoLuu(Convert.ToDateTime(dateEditNgayBaoLuu.EditValue), (31 * 6)).ToString("dd/MM/yyyy", culture);
                    }
                    else
                    {
                        lblKetQua.Text = "Bạn không thể được bảo lưu do thời gian học của bạn vượt quá 1/2 trên tổng thời gian của khóa học.";
                        pnlTop3.Enabled = false;
                    }
                }
                else
                {
                    MessageBox.Show("Học viên đã được bảo lưu");
                    pnlTop.Enabled = true;
                    pnlTop2.Enabled = false;
                    pnlTop3.Enabled = false;
                    return;
                }
                //------------------------------------------------------------------------------------------------------------------
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region "Coding"
        private void LoadControl()
        {
            try
            {
                LoadKhoaHoc();
                LoadBaoLuu();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadBaoLuu()
        {
            try
            {
                if (ds.Tables["TableBaoLuu"] != null)
                    ds.Tables["TableBaoLuu"].Clear();
                string sql = @"SELECT
                                bl.InvoiceNumber, enq.Holot, enq.Ten, dmkh.MaKhoaHoc, dmkh.TenKhoaHoc, 
                                TuNgay, bl.DenNgay, bl.SoTienBaoLuu, bl.LyDoBaoLuu, bl.UpdateUserID, bl.UpdateDate,
                                bl.Loai, bl.SoLanFeeplanBatDauChuyen, bl.ID, bl.TrangThai
                                FROM
                                BaoLuu bl INNER JOIN Invoice inv ON inv.InvoiceNumber = bl.InvoiceNumber
                                INNER JOIN Enquiry enq ON enq.EnquiryNumber = inv.EnquiryNumber
                                INNER JOIN DM_KHOAHOC dmkh ON dmkh.MaKhoaHoc = bl.MaKhoaHoc";
                mine.ExecDataAdapter(sql, conn, ds, "TableBaoLuu", gridControlDanhSachBaoLuu);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateData()
        {
            try
            {
                string sql = @"SELECT * FROM BaoLuu";
                SqlDataAdapter dabaoluu = new SqlDataAdapter(sql, conn);
                DataHelper.buildDataCommands(ref dabaoluu);
                dabaoluu.Update(ds, "TableBaoLuu");

                gridControlDanhSachBaoLuu.DataSource = ds.Tables["TableBaoLuu"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadKhoaHoc()
        {
            try
            {
                if (ds.Tables["TableKhoaHoc"] != null)
                    ds.Tables["TableKhoaHoc"].Clear();
                string sql = @"SELECT MaKhoaHoc, TenKhoaHoc FROM DM_KHOAHOC";
                mine.ExecuteDataAdapter(sql, conn, ds, "TableKhoaHoc", "MaKhoaHoc", "TenKhoaHoc", searchLookUpEditKhoaHoc);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadInvoiceByKhoaHoc(string makhoahoc)
        {
            try
            {
                if (ds.Tables["TableInvoiceByKhoaHoc"] != null)
                    ds.Tables["TableInvoiceByKhoaHoc"].Clear();
                string sql =
                    @"SELECT
                    inv.InvoiceNumber, enq.Holot, enq.Ten, dmkh.TenKhoaHoc, dmkh.SoGioHoc, dmkh.MaNgayTrongTuan
                    FROM
                    Invoice inv INNER JOIN Enquiry enq ON inv.EnquiryNumber = enq.EnquiryNumber
                    INNER JOIN DM_KHOAHOC dmkh ON dmkh.MaKhoaHoc = inv.MaLop
                    WHERE dmkh.MaKhoaHoc = '" + makhoahoc + "'";
                //mine.ExecuteDataAdapter(sql, conn, ds, "TableInvoiceByKhoaHoc", "InvoiceNumber", "Ten", searchLookUpEditInvoice);
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableInvoiceByKhoaHoc");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void LoadInvoiceByInvoiceNumberAndMaKhoaHoc(string invnumber, string makhoahoc)
        {
            try
            {
                if (ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"] != null)
                    ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Clear();
                string sql =
                    @"SELECT
                    inv.InvoiceNumber, enq.Holot, enq.Ten, dmkh.TenKhoaHoc, inv.Amount, inv.Builling,
                    dmkh.SoGioHoc, dmkh.MaNgayTrongTuan
                    FROM
                    Invoice inv INNER JOIN Enquiry enq ON inv.EnquiryNumber = enq.EnquiryNumber
                    INNER JOIN DM_KHOAHOC dmkh ON dmkh.MaKhoaHoc = inv.MaLop
                    WHERE dmkh.MaKhoaHoc = '" + makhoahoc + "'AND inv.InvoiceNumber = '" + invnumber + "'";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableInvoiceByInvoiceNumberAndMaKhoaHoc");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadInvoiceByInvoiceNumber(string invoicenumber)
        {
            try
            {
                if (ds.Tables["TableInvoiceByInvoiceNumber"] != null)
                    ds.Tables["TableInvoiceByInvoiceNumber"].Clear();
                string sql = @"SELECT enq.Holot, enq.Ten FROM Invoice inv INNER JOIN Enquiry enq
                                ON inv.EnquiryNumber = enq.EnquiryNumber
                                WHERE InvoiceNumber = '" + invoicenumber + "'";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableInvoiceByInvoiceNumber");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool CheckBaoLuuByHocVienVaKhoaHoc()
        {
            try
            {
                if (ds.Tables["TableCheck"] != null)
                    ds.Tables["TableCheck"].Clear();
                string sql = @"SELECT InvoiceNumber FROM BaoLuu WHERE InvoiceNumber = '" + Invoicenumber + 
                                "'AND MaKhoaHoc = '" + Makhoahoc + "'";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableCheck");
                if (ds.Tables["TableCheck"].Rows.Count > 0)
                    return false;
                else
                    return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        //---------------------------------------Thêm bảo lưu---------------------------------------------------------------

        private void cmdAddNew_Click(object sender, EventArgs e)
        {
            SetEditModeButton(true);
            SetEditModePanel(false);
            cmdModify.Enabled = false;
            cmdDelete.Enabled = false;
            cmdUpdate.Enabled = true;
            _insert = true;
            memoEditLyDoBaoLuu.Text = "";
        }

        private void cmdUpdate_Click(object sender, EventArgs e)
        {
            SetEditModeButton(false);
            SetEditModePanel(false);
            pnlTop.Enabled = false;
            cmdUpdate.Enabled = false;
            if (_update == true && _insert == false)
            {
                UpdateBaoLuuToDataSet(Invoicenumber, Makhoahoc, dateEditNgayBaoLuu.EditValue.ToString(),
                                        lblNgayKetThucBaoLuu.Text, memoEditLyDoBaoLuu.Text,
                                        SoTienBaoLuu(Convert.ToDouble(_amount),
                                        _sotien1hhoc, SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue))).ToString(), _userid);
                //_update = false;
            }
            else if (_insert = true && _update == false)
            {
                InsertNewBaoLuuToDataSet(Invoicenumber, Makhoahoc, dateEditNgayBaoLuu.EditValue.ToString(),
                                            lblNgayKetThucBaoLuu.Text, memoEditLyDoBaoLuu.Text,
                                            SoTienBaoLuu(Convert.ToDouble(_amount),
                                            _sotien1hhoc, SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue))).ToString(), _userid);
                //_insert = false;
            }
            
            UpdateData();
            LoadBaoLuu();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            ds.RejectChanges();
            //-----------------------------------
            SetEditModeButton(false);
            SetEditModePanel(false);
            pnlTop.Enabled = false;
            _insert = false;
            _update = false;
        }

        private void cmdModify_Click(object sender, EventArgs e)
        {
            SetEditModeButton(false);
            SetEditModePanel(false);
            pnlTop.Enabled = false;
            pnlTop2.Enabled = true;
            pnlTop3.Enabled = true;
            cmdModify.Enabled = false;
            cmdUpdate.Enabled = true;
            _update = true;

            _dr = gridViewDanhSachBaoLuu.GetFocusedDataRow();
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            _delete = true;
            SetEditModeButton(false);
            SetEditModePanel(false);
            pnlTop.Enabled = false;
            //-------------------------------------------------------------------------
            DeleteBaoLuuFromDataSet();
            //-------------------------------------------------------------------------
            UpdateData();
            LoadBaoLuu();
        }

        private void cmdPrint_Click(object sender, EventArgs e)
        {
            string invoicenumber = _dr["InvoiceNumber"].ToString();
            string makhoahoc = _dr["MaKhoaHoc"].ToString();
            PrintData(invoicenumber, makhoahoc);
        }

        private void dateEditNgayBaoLuu_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (KetQua(_ngaykhaigiang, _ngayketthuc, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)))
                {
                    lblKetQua.Text = "Bạn có thể được bảo lưu do thời gian học của bạn chưa đạt được 1/2 trên tổng thời gian của khóa học.";
                    pnlTop3.Enabled = true;
                    lblSoTienDaDong.Text = Convert.ToDouble(_amount).ToString("N0");
                    lblTenHocSinh.Text = _hoten;
                    lblPhiBaoLuu.Text = String.Format("{0:N0}", 300000);

                    _sotien1hhoc = SoTien1hHoc(Convert.ToDouble(_builling), Convert.ToInt32(_sogiohoc));
                    lblSoTien1hHoc.Text = _sotien1hhoc.ToString("N0");
                    _sotienbaoluu = SoTienBaoLuu(Convert.ToDouble(_amount), _sotien1hhoc,
                                                    SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)));
                    lblSoTienBaoLuu.Text = _sotienbaoluu.ToString("N0");
                    lblNgayKetThucBaoLuu.Text = TinhNgayKetThucBaoLuu(Convert.ToDateTime(dateEditNgayBaoLuu.EditValue), (31 * 6)).ToString("dd/MM/yyyy", culture);
                    lblSoGioDaHoc.Text = SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)).ToString();
                }
                else
                {
                    lblKetQua.Text = "Bạn không thể được bảo lưu do thời gian học của bạn vượt quá 1/2 trên tổng thời gian của khóa học.";
                    pnlTop3.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridViewDanhSachBaoLuu_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            //try
            //{
            //    SetEditModeButton(true);
            //    cmdUpdate.Enabled = false;
            //    //-----------------------------------------------------------------------
            //    /*
            //    btnDongYBaoLuu.Enabled = false;
            //    btnChinhSua.Enabled = true;
            //    btnXoa.Enabled = true;
            //     */
            //    //-----------------------------------------------------------------------
            //    DataRow dr_current = gridViewDanhSachBaoLuu.GetFocusedDataRow();
            //    _dr = dr_current;
            //    pnlTop.Enabled = false;
            //    pnlTop2.Enabled = true;
            //    pnlTop3.Enabled = true;
            //    //------------------Load Info Baoluu da chon------------------------------
            //    Invoicenumber = dr_current["InvoiceNumber"].ToString();
            //    Makhoahoc = dr_current["MaKhoaHoc"].ToString();

            //    LoadInvoiceByKhoaHoc(Makhoahoc);
            //    _sogiohoc = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][4].ToString();
            //    _mangaytrongtuan = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][5].ToString();

            //    //LoadInvoiceByInvoiceNumber(Invoicenumber);
            //    Holot = dr_current["Holot"].ToString();
            //    Ten = dr_current["Ten"].ToString();
            //    Hoten = Holot + " " + Ten;
            //    lblTenHocSinh.Text = Hoten;
            //    lblTenLop.Text = dr_current["TenKhoaHoc"].ToString();
            //    LoadInvoiceByInvoiceNumberAndMaKhoaHoc(Invoicenumber, Makhoahoc);
            //    Amount = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][4].ToString();
            //    Builling = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][5].ToString();
            //    //--------------------Go to chi tiet bao luu---------------------------------------------
            //    memoEditLyDoBaoLuu.Text = dr_current["LyDoBaoLuu"].ToString();
            //    //frmChiTiet = new frmBaoLuuHocPhiChiTiet(Makhoahoc, Invoicenumber, Hoten, Amount, Builling, Sogiohoc, Mangaytrongtuan);
            //    //frmChiTiet.ShowDialog(this);

            //    //pnlTop2.Enabled = true;
            //    //---------------------------------Info cua khoa hoc----------------------------------------------------------------
            //    LoadKhoaHocByKhoaHoc(_makhoahoc);
            //    //lblTenKhoaHoc.Text = dr_current["TenKhoaHoc"].ToString();
            //    lblNgayKhaiGiang.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][1].ToString();
            //    lblNgayKetThuc.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][2].ToString();
            //    _ngaykhaigiang = DateTime.Parse(lblNgayKhaiGiang.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
            //    _ngayketthuc = DateTime.Parse(lblNgayKetThuc.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
            //    //-------------------------------------------------------------------------------------------------------------------------
            //    dateEditNgayBaoLuu.EditValue = dr_current["TuNgay"];
            //    //int songaydahoc = SoNgayDaHoc(ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue));

            //    if (KetQua(_ngaykhaigiang, _ngayketthuc, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)))
            //    {
            //        lblKetQua.Text = "Bạn có thể được bảo lưu do thời gian học của bạn chưa đạt được 2/3 trên tổng thời gian của khóa học.";
            //        pnlTop3.Enabled = true;
            //        lblSoTienDaDong.Text = String.Format("{0:C}", Convert.ToDouble(_amount));
            //        lblTenHocSinh.Text = _hoten;
            //        lblPhiBaoLuu.Text = String.Format("{0:C}", 300000);
            //        _sotien1hhoc = SoTien1hHoc(Convert.ToDouble(_builling), Convert.ToInt32(_sogiohoc));
            //        lblSoTien1hHoc.Text = String.Format("{0:C}", _sotien1hhoc);
            //        _sotienbaoluu = SoTienBaoLuu(Convert.ToDouble(_amount), _sotien1hhoc,
            //                                        SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)));
            //        lblSoTienBaoLuu.Text = String.Format("{0:C}", _sotienbaoluu);
            //        lblSoGioDaHoc.Text = SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)).ToString();
            //        lblNgayKetThucBaoLuu.Text = TinhNgayKetThucBaoLuu(Convert.ToDateTime(dateEditNgayBaoLuu.EditValue), (31 * 6)).ToString("dd/MM/yyyy", culture);
            //    }
            //    else
            //    {
            //        lblKetQua.Text = "Bạn không thể được bảo lưu do thời gian học của bạn vượt quá 2/3 trên tổng thời gian của khóa học.";
            //        pnlTop3.Enabled = false;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        private void gridViewDanhSachBaoLuu_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                SetEditModeButton(true);
                cmdUpdate.Enabled = false;
                cmdPrint.Enabled = true;
                //-----------------------------------------------------------------------
                /*
                btnDongYBaoLuu.Enabled = false;
                btnChinhSua.Enabled = true;
                btnXoa.Enabled = true;
                 */
                //-----------------------------------------------------------------------
                if (_insert == false && _update == false && _delete == false)
                {
                    DataRow dr_current = gridViewDanhSachBaoLuu.GetFocusedDataRow();
                    _dr = dr_current;
                    if (_dr != null)
                    {
                        pnlTop.Enabled = false;
                        pnlTop2.Enabled = false;
                        pnlTop3.Enabled = false;
                        //------------------Load Info Baoluu da chon------------------------------
                        Invoicenumber = dr_current["InvoiceNumber"].ToString();
                        Makhoahoc = dr_current["MaKhoaHoc"].ToString();

                        LoadInvoiceByKhoaHoc(Makhoahoc);
                        _sogiohoc = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][4].ToString();
                        _mangaytrongtuan = ds.Tables["TableInvoiceByKhoaHoc"].Rows[0][5].ToString();

                        //LoadInvoiceByInvoiceNumber(Invoicenumber);
                        Holot = dr_current["Holot"].ToString();
                        Ten = dr_current["Ten"].ToString();
                        Hoten = Holot + " " + Ten;
                        lblTenHocSinh.Text = Hoten;
                        lblTenLop.Text = dr_current["TenKhoaHoc"].ToString();
                        LoadInvoiceByInvoiceNumberAndMaKhoaHoc(Invoicenumber, Makhoahoc);
                        Amount = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][4].ToString();
                        Builling = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][5].ToString();
                        //--------------------Go to chi tiet bao luu---------------------------------------------
                        memoEditLyDoBaoLuu.Text = dr_current["LyDoBaoLuu"].ToString();
                        //frmChiTiet = new frmBaoLuuHocPhiChiTiet(Makhoahoc, Invoicenumber, Hoten, Amount, Builling, Sogiohoc, Mangaytrongtuan);
                        //frmChiTiet.ShowDialog(this);

                        //pnlTop2.Enabled = true;
                        //---------------------------------Info cua khoa hoc----------------------------------------------------------------
                        LoadKhoaHocByKhoaHoc(_makhoahoc);
                        //lblTenKhoaHoc.Text = dr_current["TenKhoaHoc"].ToString();
                        lblNgayKhaiGiang.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][1].ToString();
                        lblNgayKetThuc.Text = ds.Tables["TableKhoaHocByKhoaHoc"].Rows[0][2].ToString();
                        _ngaykhaigiang = DateTime.Parse(lblNgayKhaiGiang.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        _ngayketthuc = DateTime.Parse(lblNgayKetThuc.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        //-------------------------------------------------------------------------------------------------------------------------
                        dateEditNgayBaoLuu.EditValue = dr_current["TuNgay"];
                        //int songaydahoc = SoNgayDaHoc(ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue));

                        if (KetQua(_ngaykhaigiang, _ngayketthuc, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)))
                        {
                            lblKetQua.Text = "Bạn có thể được bảo lưu do thời gian học của bạn chưa đạt được 1/2 trên tổng thời gian của khóa học.";
                            pnlTop3.Enabled = true;
                            lblSoTienDaDong.Text = Convert.ToDouble(_amount).ToString("N0");
                            lblTenHocSinh.Text = _hoten;
                            lblPhiBaoLuu.Text = String.Format("{0:N0}", 300000);
                            _sotien1hhoc = SoTien1hHoc(Convert.ToDouble(_builling), Convert.ToInt32(_sogiohoc));
                            lblSoTien1hHoc.Text = String.Format("{0:N0}", _sotien1hhoc);
                            _sotienbaoluu = SoTienBaoLuu(Convert.ToDouble(_amount), _sotien1hhoc,
                                                            SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)));
                            lblSoTienBaoLuu.Text = String.Format("{0:N0}", _sotienbaoluu);
                            lblSoGioDaHoc.Text = SoGioDaHoc(_ngaykhaigiang, Convert.ToDateTime(dateEditNgayBaoLuu.EditValue)).ToString();
                            lblNgayKetThucBaoLuu.Text = TinhNgayKetThucBaoLuu(Convert.ToDateTime(dateEditNgayBaoLuu.EditValue), (31 * 6)).ToString("dd/MM/yyyy", culture);
                        }
                        else
                        {
                            lblKetQua.Text = "Bạn không thể được bảo lưu do thời gian học của bạn bằng hoặc vượt quá 1/2 trên tổng thời gian của khóa học.";
                            pnlTop3.Enabled = false;
                        }

                        cmdModify.Enabled = true;
                    }
                }
                else
                {
                    _insert = false;
                    _update = false;
                    _delete = false;
                    gridViewDanhSachBaoLuu.UnselectRow(e.FocusedRowHandle);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        
        string _trangThai;
        private void gridViewDanhSachBaoLuu_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("TrangThai")) 
                _trangThai = e.Value.ToString();
        }

        #region "Code Thêm bảo lưu"

        private void LoadKhoaHocByKhoaHoc(string makhoahoc)
        {
            try
            {
                if (ds.Tables["TableKhoaHocByKhoaHoc"] != null)
                    ds.Tables["TableKhoaHocByKhoaHoc"].Clear();
                string sql = @"SELECT TenKhoaHoc, CONVERT(VARCHAR, NgayBatDau, 103), CONVERT(VARCHAR, NgayKetThuc, 103), SoGioHoc FROM DM_KHOAHOC WHERE MaKhoaHoc = '" + makhoahoc + "'";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableKhoaHocByKhoaHoc");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool KetQua(DateTime startdate, DateTime enddate, DateTime baoluudate)
        {
            try
            {
                int start = startdate.DayOfYear;
                int end = enddate.DayOfYear;
                int baoluu = baoluudate.DayOfYear;
                double kq = (double)(baoluu - start) / (end - start);
                if (kq >= ((double)1 / 2))
                    return false;
                else
                    return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        private DateTime TinhNgayKetThucBaoLuu(DateTime ngaybaoluu, int songaybaoluu)
        {
            try
            {
                return ngaybaoluu.AddDays(songaybaoluu);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return new DateTime(1, 1, 1900);
            }
        }

        private int SoGioDaHoc(DateTime startdate, DateTime baoluudate)
        {
            try
            {
                int songaydahoc = 0;
                DateTime datetemp = startdate;
                while (datetemp < baoluudate)
                {
                    if (_mangaytrongtuan == "01")
                    {
                        if (datetemp.DayOfWeek.ToString() == "Monday" || datetemp.DayOfWeek.ToString() == "Wednesday" || datetemp.DayOfWeek.ToString() == "Friday")
                        {
                            songaydahoc += 1;
                        }
                    }
                    else if (_mangaytrongtuan == "02")
                    {
                        if (datetemp.DayOfWeek.ToString() == "Tuesday" || datetemp.DayOfWeek.ToString() == "Thursday" || datetemp.DayOfWeek.ToString() == "Saturday")
                        {
                            songaydahoc += 1;
                        }
                    }
                    else if (_mangaytrongtuan == "20")
                    {
                        if (datetemp.DayOfWeek.ToString() == "Saturday" || datetemp.DayOfWeek.ToString() == "Sunday")
                        {
                            songaydahoc += 1;
                        }
                    }
                    else if (_mangaytrongtuan == "21")
                    {
                        if (datetemp.DayOfWeek.ToString() != "Saturday" && datetemp.DayOfWeek.ToString() != "Sunday")
                        {
                            songaydahoc += 1;
                        }
                    }
                    datetemp = datetemp.AddDays(1);
                }
                return songaydahoc * 2;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
            }
        }

        private double SoTien1hHoc(double builling, int sogiohoc)
        {
            try
            {
                return builling / sogiohoc;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
            }
        }

        private double SoTienBaoLuu(double sotiendadong, double sotien1hhoc, int sogiodahoc)
        {
            try
            {
                return sotiendadong - (sotien1hhoc * sogiodahoc) - 300000;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
            }
        }

        private void PrintData(string invoicenumber, string makhoahoc)
        {
            try
            {
                cmdPrint.Enabled = false;
                //Load Report
                ReportDocument rpt = new ReportDocument();
                if (GlobalVariable.WSInfo.CompanyID.ToLower() == "english")
                    rpt.Load(Application.StartupPath + "\\Report\\myrpt_BaoLuu_English.rpt");
                //Set connection
                PublicFunction.SetDBLogonForReport(rpt);
                //Set parameters
                PublicFunction.SetParameter(rpt, "@invoice_number", invoicenumber);
                PublicFunction.SetParameter(rpt, "@makhoahoc", makhoahoc);
                //View report
                frmPrintPreview frmPP = new frmPrintPreview(rpt);
                frmPP.ShowDialog();
                frmPP.Dispose();

                rpt.Dispose();
                cmdPrint.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        //---------------------------------------Insert new record bao luu to dataset---------------------------------------
        #region "Insert, edit, delete record bao luu to dataset"
        private void InsertNewBaoLuuToDataSet(string invoicenumber, string makhoahoc, string tungay, string denngay, string lydobaoluu, string sotienbaoluu, string userid)
        {
            try
            {
                LoadInvoiceByInvoiceNumberAndMaKhoaHoc(invoicenumber, makhoahoc);
                DataRow drbaoluu = ds.Tables["TableBaoLuu"].NewRow();
                drbaoluu["InvoiceNumber"] = invoicenumber;
                drbaoluu["Holot"] = Holot;
                drbaoluu["Ten"] = Ten;
                drbaoluu["MaKhoaHoc"] = Makhoahoc;
                drbaoluu["TenKhoaHoc"] = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][3].ToString();
                drbaoluu["TuNgay"] = Convert.ToDateTime(tungay);
                drbaoluu["DenNgay"] = DateTime.Parse(denngay, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                drbaoluu["SoTienBaoLuu"] = Convert.ToDouble(sotienbaoluu);
                drbaoluu["LyDoBaoLuu"] = lydobaoluu;
                drbaoluu["UpdateUserID"] = userid;
                drbaoluu["UpdateDate"] = DBNull.Value;
                drbaoluu["TrangThai"] = "Waiting";
                ds.Tables["TableBaoLuu"].Rows.Add(drbaoluu);

                gridControlDanhSachBaoLuu.DataSource = ds.Tables["TableBaoLuu"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateBaoLuuToDataSet(string invoicenumber, string makhoahoc, string tungay, string denngay, string lydobaoluu, string sotienbaoluu, string userid)
        {
            try
            {
                _dr["InvoiceNumber"] = invoicenumber;
                _dr["Holot"] = Holot;
                _dr["Ten"] = Ten;
                _dr["MaKhoaHoc"] = Makhoahoc;
                _dr["TenKhoaHoc"] = ds.Tables["TableInvoiceByInvoiceNumberAndMaKhoaHoc"].Rows[0][3].ToString();
                _dr["TuNgay"] = Convert.ToDateTime(tungay);
                _dr["DenNgay"] = DateTime.Parse(denngay, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                _dr["SoTienBaoLuu"] = Convert.ToDouble(sotienbaoluu);
                _dr["LyDoBaoLuu"] = lydobaoluu;
                _dr["UpdateUserID"] = userid;
                _dr["UpdateDate"] = DateTime.Now;
                if (_userid.Trim().ToLower() == "tuptc")
                    _dr["TrangThai"] = _trangThai;
                else 
                    _dr["TrangThai"] = "Waiting";
                //ds.Tables["TableBaoLuu"].Rows.Add(_dr);

                gridControlDanhSachBaoLuu.DataSource = ds.Tables["TableBaoLuu"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DeleteBaoLuuFromDataSet()
        {
            try
            {
                _dr.Delete();
                gridControlDanhSachBaoLuu.DataSource = ds.Tables["TableBaoLuu"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        //---------------------------------------Set Edit Mode--------------------------------------------------------------
        #region "Set Edit Mode"
        private void SetEditModeButton(bool edit)
        {
            try
            {
                cmdAddNew.Enabled = !edit;
                cmdUpdate.Enabled = edit;
                cmdDelete.Enabled = edit;
                cmdCancel.Enabled = edit;
                cmdModify.Enabled = edit;
                cmdPrint.Enabled = edit;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SetEditModePanel(bool editpanel)
        {
            try
            {
                pnlTop.Enabled = !editpanel;
                pnlTop2.Enabled = editpanel;
                pnlTop3.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #endregion
    }
}
